package com.carbohydrate42.kotlin_compose_demo.compose

import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import com.carbohydrate42.kotlin_compose_demo.config.RoomConfig
import com.carbohydrate42.kotlin_compose_demo.constant.Common
import com.carbohydrate42.kotlin_compose_demo.entity.User
import com.carbohydrate42.kotlin_compose_demo.viewModel.TryRoomOrmViewModel
import kotlinx.coroutines.launch

@Preview(showSystemUi = true, showBackground = true)
@Composable
fun TryRoomOrm(
    tryRoomOrmViewModel: TryRoomOrmViewModel = TryRoomOrmViewModel()
) {

    /**
     * 创建 compose 要用的协程作用域
     */
    val coroutineScope = rememberCoroutineScope()

    var dataBaseStr: String by remember { mutableStateOf("") }

    var count: Int by remember { mutableStateOf(0) }


    Column() {
        Row() {
            Button(onClick = {
                coroutineScope.launch {
                    RoomConfig.testDatabase.userDao().save(
                        User(
                            id = null,
                            name = "name1",
                            password = "password1",
                            authToken = "authToken1"
                        )
                    )
                }
            }) {
                Text(text = "create")
            }
            Button(onClick = {
                coroutineScope.launch {
                    val users = RoomConfig.testDatabase.userDao().findAll()
                    Log.d(Common.ANDROID_LOG_TAG.label, users.toString())
                    dataBaseStr = users.toString()
                }
            }) {
                Text(text = "read")
            }

            Button(onClick = { count++ }) {
                Text(text = count.toString())
            }
        }

        Text(text = dataBaseStr)

    }


    Column() {

        Button(onClick = { tryRoomOrmViewModel.createOneUser() }) {
            Text(text = "create one user and show")
        }

        Text(text = tryRoomOrmViewModel.dataBaseStr)
    }
}